﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Bll;
using Pyramid.Models;
using System.Data.Entity;

namespace Pyramid.Controllers
{
	public class CustomerController : PaymentBaseController
	{
		private readonly CustomerHelper _helper = new CustomerHelper();
		private readonly SelectListHelper _dropDownListHelper = SelectListHelper.NewInstance;

		#region customer base info

		public ActionResult List(CustomerQueryModel model)
		{
			return View(PrepareForListView(model));
		}

		public ActionResult SelectList(CustomerQueryModel model)
		{
			return View(PrepareForListView(model));
		}

		public ActionResult SelectList2(CustomerQueryModel model)
		{
			return View(PrepareForListView(model));
		}

		private List<Customer> PrepareForListView(CustomerQueryModel model)
		{
			var customers = _helper.Query(model, User);

			var currentPage = (model.PageNum ?? 1) - 1;
			var pageSize = model.NumPerPage ?? 20;

			var vm = new PagerModel
			{
				PageSize = pageSize,
				CurrentPageIndex = currentPage,
				TotalCount = customers.Count()
			};
			ViewBag.Bag = vm;
			ViewBag.QueryModel = model;
			return customers.OrderBy(x => x.Id).Skip(currentPage*pageSize).Take(pageSize).ToList();
		}

		public ActionResult Create()
		{
			var model = new Customer
				{
					Birthday = DateTime.Parse("1982-01-01"),
					CreateUserId = User.UserId,
					CreateTime = DateTime.Now,
					EditUserId = User.UserId,
					EditTime = DateTime.Now
				};
			return View("Edit", model);
		}

		public ActionResult Edit(int id)
		{
			var model = Db.Customers.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(Customer model)
		{
			if (Db.Customers.Any(x => x.Id != model.Id && x.Code == model.Code))
			{
				return JError("顾客编号已被占用，请修改！");
			}

			if (model.Id == 0)
			{
				switch (User.UserType)
				{
					case UserTypes.AdminCenter:
						model.AdminCenterId = User.ExtInfoId;
						break;
					case UserTypes.MemberCenter:
						{
							model.MemberCenterId = User.ExtInfoId;
							var memberCenter = Db.MemberCenters.Single(x => x.Id == User.ExtInfoId);
							model.AdminCenterId = memberCenter.AdminCenterId;
						}
						break;
				}

				model.CreateUserId = User.UserId;
				model.CreateTime = DateTime.Now;
				model.EditUserId = User.UserId;
				model.EditTime = DateTime.Now;
				Db.Customers.Add(model);
			}
			else
			{
				model.EditUserId = User.UserId;
				model.EditTime = DateTime.Now;
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();

			return JSuccess("操作成功！", "tab_ccm_archive");
		}

		public ActionResult Delete(int id)
		{
			var model = new Customer {Id = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", "tab_ccm_archive");
		}

		#endregion

		#region customer account

		public ActionResult AccountList(CustomerQueryModel model)
		{
			return View(PrepareForListView(model));
		}

		public ActionResult SetAccount(int customerId)
		{
			var customer = _helper.Single(customerId);
			ViewBag.Account = string.IsNullOrWhiteSpace(customer.UserId) ?
								new Account {Id = 0, ExtInfoId = customer.Id, ExtInfoName = customer.FullName, UserType = (int) UserTypes.Customer, FullName = customer.FullName}
								: Db.Accounts.Include(x => x.Roles).First(x => x.UserId == customer.UserId);

			return View(customer);
		}

		[HttpPost]
		public ActionResult SetAccount(int customerId, Account model, int[] selectedRoleIds)
		{
			var helper = AccountHelper.NewInstance;
			return helper.InsertOrUpdate4Customer(customerId, model, selectedRoleIds) ? JSuccess("账号设置成功！", "tab_ccm_ccaccount") : JError(helper.Message);
		}

		#endregion

		#region customer finance

		public ActionResult PaymentList(PaymentQueryModel model)
		{
			model.PayerType = (int) PayerTypes.Customer;
			return View(PrepareForPaymentListView(model));
		}

		public ActionResult CreatePaymentApply()
		{
			var record = new PayeeRecord { ApplyTime = DateTime.Now, ApplyUserId = User.UserId, ApplyUserName = User.FullName, PayerType = (int)PayerTypes.Customer };
			ViewBag.FinanceProjects = _dropDownListHelper.FinanceProjects(PayerTypes.Customer);
			return View("EditPaymentApply", record);
		}

		public ActionResult EditPaymentApply(int id)
		{
			var record = PaymentHelper.NewInstance.Single(id);
			ViewBag.FinanceProjects = _dropDownListHelper.FinanceProjects(PayerTypes.Customer);
			return View(record);
		}

		[HttpPost]
		public ActionResult EditPaymentApply(PayeeRecord model)
		{
			model.PayerType = (int)PayerTypes.Customer;

			PaymentHelper.NewInstance.InsertOrUpdate(model, User);
			return JSuccess("操作成功！", "tab_ccm_payment");
		}

		public ActionResult DeletePaymentApply(int id)
		{
			var helper = PaymentHelper.NewInstance;
			return helper.Delete(id) ? JSuccess("删除成功！", "tab_ccm_payment") : JError(helper.Message);
		}

		#endregion
	}
}